package com.haoze.nurseapp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.haoze.common.enumeration.StateEnum;
import com.haoze.common.model.OrdersFileIndexDataEntity;
import com.haoze.common.model.OrdersFileIndexEntity;
import com.haoze.common.model.TaskExecuteBatchEntity;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.DateUtil;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurseapp.dao.*;
import com.haoze.nurseapp.dto.TaskFileDTO;
import com.haoze.nurseapp.dto.TaskFileFromViewDTO;
import com.haoze.nurseapp.dto.task.TaskExecuteDetailDTO;
import com.haoze.nurseapp.enumeration.*;
import com.haoze.nurseapp.model.*;
import com.haoze.nurseapp.service.NurseFileIndexService;
import com.haoze.nurseapp.service.NursePatientOrderService;
import com.haoze.nurseapp.service.TransfusionService;
import com.haoze.nurseapp.service.feign.PatientOrderService;
import com.haoze.nurseapp.vo.Element;
import com.haoze.nurseapp.vo.EmrFile;
import com.haoze.nurseapp.vo.EmrFileData;
import com.haoze.nurseapp.vo.batch.PuncureChannleVo;
import oracle.sql.TIMESTAMP;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Clob;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TransfusionServiceImpl implements TransfusionService {

    private static final Logger logger = LoggerFactory.getLogger(TransfusionServiceImpl.class);

    @Resource
    EmrFileIndexMapper emrFileIndexMapper;

    @Resource
    TaskExecuteDetailMapper taskExecuteDetailMapper;

    @Resource
    TaskExecuteBatchMapper taskExecuteBatchMapper;

    @Resource
    TaskExecuteMapper taskExecuteMapper;

    @Resource
    NurseFileIndexService fileIndexService;

    @Resource
    NursePatientOrderService patientOrderService;

    @Resource
    PatientOrderService patientOrderServiceFeign;

    @Resource
    TransfusionMapper transfusionMapper;

    @Resource
    NurseFileIndexDataMapper nurseFileIndexDataMapper;

    @Resource
    OrdersFileIndexDataMapper ordersFileIndexDataMapper;

    @Resource
    PuncureChannleMapper puncureChannleMapper;


    @Override
    public Result queryFileIdByBarCode(String qrCode, String nodeName) {
        String nodeId = null;
        if ("infusionCenter".equals(nodeName)) {
            nodeId = WorkSpaceEnum.INFUSION_CENTER.getNodeId();
        } else if ("infusionCompleted".equals(nodeName)) {
            nodeId = WorkSpaceEnum.INFUSION_COMPLETED.getNodeId();
        }
        try {
            //根据barCode查询对应的文书ID
            TaskExecuteDetailEntity taskExecuteDetailEntity = emrFileIndexMapper.queryInfoByBarCode(qrCode, nodeId);
            if (taskExecuteDetailEntity == null) {
                return ResultGenerator.genFailedResult("未找到该二维码对应数据");
            } else {
//                if (TaskBatchStateEnum.TASK_BATCH_UNPASS.getEnumValue().equals(taskExecuteDetailEntity.getStatus())) {
                //根据文书ID获取模板数据树形结构
                EmrFile emrFile = fileIndexService.getFileIndex(taskExecuteDetailEntity.getEmrFileId());
                if (ConstsEnum.TASK_STATUS_PAUSE.getIndex().equals(taskExecuteDetailEntity.getStatus())) {
                    hideEmrFile(emrFile);
                }
                return ResultGenerator.genOkResult(emrFile);
//                } else {
//                    return ResultGenerator.genFailedResult("当前任务批次已完成");
//                }
            }

        } catch (Exception e) {
            logger.error("参数 {}", qrCode, e);
        }
        return ResultGenerator.genFailedResult("获取失败");

    }

    private void hideEmrFile(EmrFile emrFile) {
        List<EmrFileData> emrFileDataList = emrFile.getEmrFileDataList();

        String speedCode = "syzx_speed";
        String speedValue = transfusionMapper.queryVarvalue(speedCode);
        String speed = "";
        String emrFileId = "";

        Stack<EmrFileData> stack = new Stack<>();
        for (int i = 0; i < emrFileDataList.size(); i++) {
            EmrFileData topEmrFileData = emrFileDataList.get(i);
            stack.push(topEmrFileData);
            while (!stack.empty()) {
                EmrFileData emrFileData = stack.pop();
                OrdersFileIndexDataEntity dataEntity = emrFileData.getFileIndexDataEntity();

                if (dataEntity.getElementId().equals(speedValue)) {
                    speed = dataEntity.getDataValue();
                    emrFileId = dataEntity.getEmrFileId();
                }

                dataEntity.setShowIdentification(StateEnum.SHOW_IDENTIFICATION_NO.getValue());
                List<EmrFileData> subEmrFileDataList = emrFileData.getEmrFileDataList();
                int j = subEmrFileDataList.size();
                while (--j >= 0) {
                    stack.push(subEmrFileDataList.get(j));
                }
            }
        }
        List<Map<String, String>> tplDetailList = emrFileIndexMapper.getTplDetailListByNodeId(WorkSpaceEnum.INFUSION_CENTER.getNodeId());
        Map<String, String> tempMap = new HashMap<>();
        List<Map<String, String>> newList = tplDetailList.stream().map(map -> {
            String newId = UUIDUtil.randomString();
            String oldId = map.get("FILE_INDEX_DATA_ID");
            String oldParentId = map.get("PARENT_FILE_INDEX_DATA_ID");
            map.put("FILE_INDEX_DATA_ID", newId);
            tempMap.put(oldId, newId);
            if (tempMap.get(oldParentId) != null) {
                map.put("PARENT_FILE_INDEX_DATA_ID", tempMap.get(oldParentId));
            }
            return map;
        }).collect(Collectors.toList());
        List<EmrFileData> fileDataList = convertData(newList);
        List<EmrFileData> newFileData = buildTreeData(fileDataList, null);
        emrFileDataList.addAll(newFileData);

        if (StringUtils.isNotBlank(speed)) {
            this.getSurplus(emrFileId, speed);
        }
    }


    private List<EmrFileData> convertData(List<Map<String, String>> list) {
        return list.parallelStream().map(map -> {
            EmrFileData data = new EmrFileData();
            OrdersFileIndexDataEntity dataEntity = new OrdersFileIndexDataEntity();
            dataEntity.setFileIndexDataId(map.get("FILE_INDEX_DATA_ID"));
            dataEntity.setSortId(Integer.parseInt(map.get("SORT_ID")));
            dataEntity.setElementId(map.get("ELEMENT_ID"));
            dataEntity.setParentElementId(map.get("PARENT_ELEMENT_ID"));
            dataEntity.setQuoteDatasetId(map.get("QUOTE_DATASET_ID"));
            dataEntity.setQuoteElementId(map.get("QUOTE_ELEMENT_ID"));
            dataEntity.setParentFileIndexDataId(map.get("PARENT_FILE_INDEX_DATA_ID"));
            dataEntity.setBaseTplDetailId(map.get("BASE_TPL_DETAIL_ID"));
            dataEntity.setQuoteTplDetailId(map.get("QUOTE_TPL_DETAIL_ID"));
            dataEntity.setDataCode(StringUtils.isBlank(map.get("DATA_VALUE")) ? "" : map.get("DATA_CODE"));
            dataEntity.setDataValue(StringUtils.isBlank(map.get("DATA_VALUE")) ? "" : map.get("DATA_VALUE"));
            dataEntity.setPrintIdentification(map.get("PRINT_IDENTIFICATION"));
            dataEntity.setShowIdentification(map.get("SHOW_IDENTIFICATION"));
            dataEntity.setDeleteIdentification(map.get("DELETE_IDENTIFICATION"));
            dataEntity.setElementProperty(map.get("ELEMENT_PROPERTY"));
            dataEntity.setMedicalId(map.get("MEDICAL_ID"));
            dataEntity.setUnit(map.get("UNIT"));
            dataEntity.initAdd();
            data.setFileIndexDataEntity(dataEntity);
            data.setTplDetailId(map.get("TPL_DETAIL_ID"));

            // 补充数据元属性
            Element element = new Element();
            element.setId(map.get("ELEMENT_ID"));
            element.setName(map.get("ELEMENT_NAME"));
            element.setType(map.get("ELEMENT_DATA_TYPE_ID"));
            element.setMin(map.get("MIN_VALUE") == null ? null : Double.parseDouble(map.get("MIN_VALUE")));
            element.setMax(map.get("MAX_VALUE") == null ? null : Double.parseDouble(map.get("MAX_VALUE")));
            element.setUnit(map.get("ELEMENT_UNIT"));
            element.setVarCode(map.get("VAR_CODE"));
            element.setMedicalId(dataEntity.getMedicalId());
            element.setFormat(map.get("ELEMENT_PROPERTY_FORMAT"));
            element.setElementPropertyFormat(map.get("ELEMENT_PROPERTY_FORMAT"));
            data.setElement(element);

            data.setEmrFileDataList(new ArrayList<>());
            return data;
        }).collect(Collectors.toList());
    }

    private List<EmrFileData> convertData2(List<Map<String, Object>> list) {
        return list.parallelStream().map(map -> {
            EmrFileData data = new EmrFileData();
            OrdersFileIndexDataEntity dataEntity = new OrdersFileIndexDataEntity();
            dataEntity.setFileIndexDataId((String) map.get("FILE_INDEX_DATA_ID"));
            try {
                if (map.get("GMT_CREATE") instanceof TIMESTAMP)
                    dataEntity.setCreateTime(((TIMESTAMP) map.get("GMT_CREATE")).timestampValue());
                else
                    dataEntity.setCreateTime((Timestamp) map.get("GMT_CREATE"));
            } catch (SQLException e) {
                logger.error("转换对象出错。", e);
            }
            try {
                if (map.get("GMT_MODIFY") instanceof TIMESTAMP)
                    dataEntity.setModifyTime(((TIMESTAMP) map.get("GMT_MODIFY")).timestampValue());
                else
                    dataEntity.setModifyTime((Timestamp) map.get("GMT_MODIFY"));
            } catch (SQLException e) {
                logger.error("转换对象出错。", e);
            }
            dataEntity.setSortId((map.get("SORT_ID")) == null ? 0 : ((Number) map.get("SORT_ID")).intValue());
            dataEntity.setElementId((String) map.get("ELEMENT_ID"));
            dataEntity.setParentElementId((String) map.get("PARENT_ELEMENT_ID"));
            dataEntity.setQuoteDatasetId((String) map.get("QUOTE_DATASET_ID"));
            dataEntity.setQuoteElementId((String) map.get("QUOTE_ELEMENT_ID"));
            dataEntity.setDataCode((String) map.get("DATA_CODE"));
            dataEntity.setParentFileIndexDataId((String) map.get("PARENT_FILE_INDEX_DATA_ID"));
            dataEntity.setBaseTplDetailId((String) map.get("BASE_TPL_DETAIL_ID"));
            dataEntity.setQuoteTplDetailId((String) map.get("QUOTE_TPL_DETAIL_ID"));
            String dataValue = "";
            if (map.get("DATA_VALUE_STR") != null) {
                dataValue = (String) map.get("DATA_VALUE_STR");
            } else {
                try {
                    if (map.get("DATA_VALUE") != null) {
                        if (map.get("DATA_VALUE") instanceof Clob) {
                            Clob clob = (Clob) map.get("DATA_VALUE");
                            BufferedReader reader = new BufferedReader(clob.getCharacterStream());
                            dataValue = FileCopyUtils.copyToString(reader);
                        } else
                            dataValue = (String) map.get("DATA_VALUE");
                    }
                } catch (SQLException | IOException e) {
                    logger.error("转换对象出错。", e);
                }
            }
            dataEntity.setDataValue(dataValue);
            dataEntity.setPrintIdentification((String) map.get("PRINT_IDENTIFICATION"));
            dataEntity.setShowIdentification((String) map.get("SHOW_IDENTIFICATION"));
            dataEntity.setDeleteIdentification((String) map.get("DELETE_IDENTIFICATION"));
            dataEntity.setElementProperty((String) map.get("ELEMENT_PROPERTY"));
            dataEntity.setMedicalId((String) map.get("MEDICAL_ID"));
            dataEntity.setUnit((String) map.get("UNIT"));
            data.setNeedChanged(map.get("NEED_CHANGED") == null ? "1" : map.get("NEED_CHANGED").toString());
            data.setFileIndexDataEntity(dataEntity);
            data.setTplDetailId((String) map.get("TPL_DETAIL_ID"));
            // 补充权限调用属性
            if (map.get("TPL_DETAIL_ROLE_ID") != null) {
                EmrTemplateDetailRoleEntity roleEntity = new EmrTemplateDetailRoleEntity();
                roleEntity.setEditRoleType((String) map.get("EDIT_ROLE_TYPE"));
                roleEntity.setEditRoleId((String) map.get("EDIT_ROLE_ID"));
                roleEntity.setEditDeptId((String) map.get("EDIT_DEPT_ID"));
                roleEntity.setShowRoleType((String) map.get("SHOW_ROLE_TYPE"));
                roleEntity.setShowRoleId((String) map.get("SHOW_ROLE_ID"));
                roleEntity.setShowDeptId((String) map.get("SHOW_DEPT_ID"));
                roleEntity.setPrintRoleType((String) map.get("PRINT_ROLE_TYPE"));
                roleEntity.setPrintRoleId((String) map.get("PRINT_ROLE_ID"));
                roleEntity.setPrintDeptId((String) map.get("PRINT_DEPT_ID"));
                roleEntity.setRefState((String) map.get("REF_STATE"));
                roleEntity.setRefRoleType((String) map.get("REF_ROLE_TYPE"));
                roleEntity.setRefRoleId((String) map.get("REF_ROLE_ID"));
                roleEntity.setRefDeptId((String) map.get("REF_DEPT_ID"));
                data.setRoleEntity(roleEntity);
            }
            // 补充数据元属性
            Element element = new Element();
            element.setId((String) map.get("ELEMENT_ID"));
            element.setName((String) map.get("ELEMENT_NAME"));
            element.setType((String) map.get("ELEMENT_DATA_TYPE_ID"));
            element.setMin(map.get("MIN_VALUE") == null ? null : ((Number) map.get("MIN_VALUE")).doubleValue());
            element.setMax(map.get("MAX_VALUE") == null ? null : ((Number) map.get("MAX_VALUE")).doubleValue());
            element.setUnit(map.get("ELEMENT_UNIT") == null ? null : map.get("ELEMENT_UNIT").toString());
            element.setVarCode((String) map.get("VAR_CODE"));
            element.setMedicalId(dataEntity.getMedicalId());
            element.setFormat((String) map.get("ELEMENT_PROPERTY_FORMAT"));
            element.setElementPropertyFormat((String) map.get("ELEMENT_PROPERTY_FORMAT"));
            element.setIsPreDiag(map.get("IS_PRE_DIAG") == null ? null : map.get("IS_PRE_DIAG").toString());
            data.setElement(element);

            data.setEmrFileDataList(new ArrayList<>());
            return data;
        }).collect(Collectors.toList());
    }

    /**
     * 构造病历数据树
     *
     * @param list                  病历数据
     * @param parentFileIndexDataId 顶级数据节点ID 可以为null
     * @return
     */
    private List<EmrFileData> buildTreeData(List<EmrFileData> list, String parentFileIndexDataId) {
        List<EmrFileData> topList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            EmrFileData node = list.get(i);
            node.setEmrFileDataList(new ArrayList<>());
            if (node.getFileIndexDataEntity().getParentFileIndexDataId() == null
                    || node.getFileIndexDataEntity().getParentFileIndexDataId().equals(parentFileIndexDataId)) {
                node.setPath("");
                topList.add(node);
                continue;
            }
            for (int j = 0; j < i; j++) {
                EmrFileData parent = list.get(j);
                if (parent.getFileIndexDataEntity().getFileIndexDataId().equals(node.getFileIndexDataEntity().getParentFileIndexDataId())) {
                    node.setPath(parent.getPath() + "," + parent.getFileIndexDataEntity().getFileIndexDataId());
                    parent.getEmrFileDataList().add(node);
                    break;
                }
            }
        }
        return topList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result savePiercing(TaskFileFromViewDTO taskFileFromViewDTO) {
        //获取当前用户
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        //点击确认按钮时查询当前任务节点明细是否已执行，若未执行则修改为已执行，若已执行则不作操作
        //根据barCode获取当前任务节点操作明细数据
        TaskExecuteBatchEntity taskExecuteDetailEntity = taskExecuteDetailMapper.queryInfoByBarCode(taskFileFromViewDTO.getQrCode());
        String message = "";
        if (taskExecuteDetailEntity != null) {
            if (TaskStatusEnum.STATUS_SUSPEND.getValue().equals(taskExecuteDetailEntity.getStatus())) {
                // 更新状态为执行
                taskExecuteDetailEntity.setStatus(TaskStatusEnum.STATUS_EXECUTING.getValue());
                taskExecuteDetailEntity.setStartDatetime(new Timestamp(new Date().getTime()));
                taskExecuteDetailEntity.setStopDatetime(new Timestamp(new Date().getTime()));
                taskExecuteBatchMapper.updateByPrimaryKeySelective(taskExecuteDetailEntity);
                message = fileIndexService.saveFileIndex(taskFileFromViewDTO.getEmrFile());
            } else {

                TaskFileDTO taskFileDTO = new TaskFileDTO();
                taskFileDTO.setTaskExecuteDetailEntity(taskExecuteDetailEntity);
                taskFileDTO.setTaskFileFromViewDTO(taskFileFromViewDTO);
                taskFileDTO.setUserId(userId);
                message = patientOrderServiceFeign.executeTask(taskFileDTO);
            }
        } else {
            message = fileIndexService.saveFileIndex(taskFileFromViewDTO.getEmrFile());
        }
        return ResultGenerator.genOkResult(message);
    }

    @Override
    public List getAllInfsion(String barCode, String inpatNum) {
        // 根据传递进来的barCode或QrCode获取当前病人入院号
        Map<String, Object> resultMap = new HashMap<String, Object>(2);
        if (StringUtils.isBlank(inpatNum)) {
            inpatNum = transfusionMapper.queryInfoByBarCode(barCode);
        }
        // 根据入院号获取当前病人信息（姓名，入院号，年龄，床号，性别）
        Map<String, String> patientMap = transfusionMapper.queryPatientInfo(inpatNum);
        // 根据当前病人入院号获取该病人未完成的输液流程明细，获取其中的文书id
        List<Map<String, Object>> emrFileIds = transfusionMapper.queryEmrFileIds(inpatNum, WorkSpaceEnum.INFUSION_CENTER.getNodeId());
        List<FileIndexDataSmallEntity> list = transfusionMapper.getFileIndexData(emrFileIds);

        for (Map map : emrFileIds) {
            String surplus = "0";
            for (FileIndexDataSmallEntity smallEntity : list) {
                if (map.get("emrFileId").toString().equals(smallEntity.getEmrFileId())) {
                    if (smallEntity.getVarCode().equals("syzx_node")) {
                        map.put("node", smallEntity.getDataValue() == null ? "-" : smallEntity.getDataValue());
                    } else if (smallEntity.getVarCode().equals("syzx_position")) {
                        map.put("position", smallEntity.getDataValue() == null ? "" : smallEntity.getDataValue());
                    } else if (smallEntity.getVarCode().equals("syzx_tool")) {
                        map.put("tool", smallEntity.getDataValue() == null ? "" : smallEntity.getDataValue());
                    } else if (smallEntity.getVarCode().equals("syzx_passstate")) {
                        map.put("state", smallEntity.getDataValue() == null ? "" : smallEntity.getDataValue());
                    } else if (smallEntity.getVarCode().equals("syzx_speed")) {
                        map.put("speed", smallEntity.getDataValue() == null ? "1" : smallEntity.getDataValue());
                        map.put("unit", smallEntity.getUnit() == null ? "滴/分钟" : smallEntity.getUnit());
                    } else if (smallEntity.getVarCode().equals("sy_syl")) {
                        surplus = StringUtils.isBlank(smallEntity.getDataValue()) ? "0" : smallEntity.getDataValue();
                    }
                    Map<String, Object> endInfusionMap = endInfusionInfo(map.get("emrFileId").toString());
                    map.put("endInfusionMap", endInfusionMap);
                }
            }

            // 获取组医嘱药品
            List<Map<String, String>> drugList = transfusionMapper.queryDurgsByOrderNo(inpatNum, map.get("taskExecuteId").toString());
            map.put("drugs", drugList);

            // 计算滴速
            Float milliliter = 0.0f;
            int sum = 0;
            for (Map<String, String> drugMap : drugList) {
                if ("g".equalsIgnoreCase(drugMap.get("unit").toString())) {
                    milliliter += Float.parseFloat(drugMap.get("itemDosage").toString());
                } else if ("ml".equalsIgnoreCase(drugMap.get("unit").toString())) {
                    sum += Integer.parseInt(drugMap.get("itemDosage").toString());
                }
            }
            if ("滴/分钟".equalsIgnoreCase(map.get("unit").toString())) {
                Float seconds = (milliliter / Float.parseFloat(map.get("speed").toString())) * 60 * 20;
                map.put("seconds", seconds);
            } else if ("ml/h".equalsIgnoreCase(map.get("unit").toString())) {
                Float seconds = (milliliter / Float.parseFloat(map.get("speed").toString())) * 60 * 60;
                map.put("seconds", seconds);
            }
            //计算剩余量百分比
            float surplusPercent = 0.0f;
            if (sum != 0) {
                surplusPercent = (sum - Integer.parseInt(surplus)) / sum;
            } else {
                surplusPercent = 0.0f;
            }
            map.put("surplus", surplusPercent);
            // 组装节点
            if (resultMap.containsKey(map.get("node").toString())) {
                List nodes = (List) resultMap.get(map.get("node").toString());
                nodes.add(map);
            } else {
                List nodes = new ArrayList();
                nodes.add(map);
                resultMap.put(map.get("node").toString(), nodes);
            }
        }

        // List resultList = resultMap.values().stream().collect(Collectors.toList());
        List resultList = new ArrayList();
        for (String node : resultMap.keySet()) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("index", node);
            map.put("node", resultMap.get(node));
            resultList.add(map);
        }

        return resultList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEndInfusion(Map<String, Object> qrCodeMap) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //根据barCode或QrCode获取当前任务节点
        String qrCode = (String) qrCodeMap.get("qrCode");
        EmrFile emrFile = (EmrFile) qrCodeMap.get("emrFile");
        //TaskExecuteDetailEntity taskExecuteDetailEntity = transfusionMapper.queryTaskExecuteDetail(qrCode, WorkSpaceEnum.INFUSION_COMPLETED.getNodeId());
        TaskExecuteDetailDTO queryTaskExecuteDetailInfo=transfusionMapper.queryTaskExecuteDetailInfo(qrCode, WorkSpaceEnum.INFUSION_COMPLETED.getNodeId());
        if (queryTaskExecuteDetailInfo != null) {
            fileIndexService.saveFileIndex(emrFile);
            patientOrderService.createNextTaskNode(queryTaskExecuteDetailInfo.getTaskExecuteDetailId(),queryTaskExecuteDetailInfo.getBatchNo(), userId, queryTaskExecuteDetailInfo.getGroupId() == null ? "" : queryTaskExecuteDetailInfo.getGroupId(), "", null,qrCode,null);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result markBackDrug(Map<String, String> qrCodeMap) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        String returnTimeCode = "jpsy_tysj";
        String returnDrugsCode = "jpsy_ty";
        String reasonCode = "jpsy_tyyy";
        String nurseCode = StateEnum.SIGN_CODE.getValue();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String currentDate = sdf.format(date);
        //获取当前需要退药的qrCode   静配收药        退药时间element_id  0f14538d1e4446a89f9cf93aa87f45eb    退药原因element_id  b6a361c574c0456b99babf20c32e35d2
        String qrCode = qrCodeMap.get("qrCode");     //流程编号
        String dataCode = qrCodeMap.get("dataCode");     //退药原因编号
        String dataValue = qrCodeMap.get("dataValue");       //退药原因
        TaskExecuteDetailEntity taskExecuteDetailEntity = taskExecuteMapper.queryTaskExecute(qrCode, WorkSpaceEnum.STATIC_DRUG_COLLECTION.getNodeId());
        FileIndexDataEntity fileIndexDataEntity = new FileIndexDataEntity();
        FileIndexDataEntity reDrugsFileDetailEntity = new FileIndexDataEntity();
        FileIndexDataEntity newNurse = new FileIndexDataEntity();
        if (taskExecuteDetailEntity != null) {
            //获取退药文书明细主记录
            String parPrimaryKey = null;
            String parentPrikey = UUIDUtil.randomString();
            FileIndexDataEntity parentFileIndexDataEntity = nurseFileIndexDataMapper.getFileIndexData(taskExecuteDetailEntity.getEmrFileId(), returnDrugsCode);
            if (!StateEnum.PRINT_IDENTIFICATION.getValue().equals(parentFileIndexDataEntity.getPrintIdentification())) {
                parentFileIndexDataEntity.setPrintIdentification("0");
                parentFileIndexDataEntity.setGmtModify(new Timestamp(date.getTime()));
                nurseFileIndexDataMapper.updateByPrimaryKeySelective(parentFileIndexDataEntity);
                parPrimaryKey = parentFileIndexDataEntity.getFileIndexDataId();
            } else {
                FileIndexDataEntity newParent = new FileIndexDataEntity();
                BeanUtils.copyProperties(parentFileIndexDataEntity, newParent);
                newParent.setFileIndexDataId(parentPrikey);
                newParent.setGmtCreate(new Timestamp(date.getTime()));
                newParent.setGmtModify(new Timestamp(date.getTime()));
                nurseFileIndexDataMapper.insert(newParent);
                parPrimaryKey = parentPrikey;
            }
            //获取当前任务节点文书,根据文书ID和退药时间数据元ID获取当前文书明细
            FileIndexDataEntity reTimeFileIndexDataEntity = nurseFileIndexDataMapper.getFileIndexDataInfo(taskExecuteDetailEntity.getEmrFileId(), returnTimeCode, parentFileIndexDataEntity.getFileIndexDataId());
            if (!StateEnum.PRINT_IDENTIFICATION.getValue().equals(reTimeFileIndexDataEntity.getPrintIdentification())) {
                reTimeFileIndexDataEntity.setDataValue(currentDate);
                reTimeFileIndexDataEntity.setPrintIdentification("0");
                reTimeFileIndexDataEntity.setGmtModify(new Timestamp(date.getTime()));
                nurseFileIndexDataMapper.updateByPrimaryKeySelective(reTimeFileIndexDataEntity);
            } else {
                BeanUtils.copyProperties(reTimeFileIndexDataEntity, fileIndexDataEntity);
                fileIndexDataEntity.setFileIndexDataId(UUIDUtil.randomString());
                fileIndexDataEntity.setParentFileIndexDataId(parentPrikey);
                fileIndexDataEntity.setDataValue(currentDate);
                fileIndexDataEntity.setGmtCreate(new Timestamp(date.getTime()));
                fileIndexDataEntity.setGmtModify(new Timestamp(date.getTime()));
                nurseFileIndexDataMapper.insert(fileIndexDataEntity);
            }
            //获取退药原因明细记录
            FileIndexDataEntity reasonFileIndexDataEntity = nurseFileIndexDataMapper.getFileIndexDataInfo(taskExecuteDetailEntity.getEmrFileId(), reasonCode, parentFileIndexDataEntity.getFileIndexDataId());
            if (!StateEnum.PRINT_IDENTIFICATION.getValue().equals(reasonFileIndexDataEntity.getPrintIdentification())) {
                reasonFileIndexDataEntity.setDataCode(dataCode);
                reasonFileIndexDataEntity.setDataValue(dataValue);
                reasonFileIndexDataEntity.setPrintIdentification("0");
                reasonFileIndexDataEntity.setGmtModify(new Timestamp(date.getTime()));
                nurseFileIndexDataMapper.updateByPrimaryKeySelective(reasonFileIndexDataEntity);
            } else {
                BeanUtils.copyProperties(reasonFileIndexDataEntity, reDrugsFileDetailEntity);
                reDrugsFileDetailEntity.setFileIndexDataId(UUIDUtil.randomString());
                reDrugsFileDetailEntity.setParentFileIndexDataId(parentPrikey);
                reDrugsFileDetailEntity.setDataCode(dataCode);
                reDrugsFileDetailEntity.setDataValue(dataValue);
                reDrugsFileDetailEntity.setGmtCreate(new Timestamp(date.getTime()));
                reDrugsFileDetailEntity.setGmtModify(new Timestamp(date.getTime()));
                nurseFileIndexDataMapper.insert(reDrugsFileDetailEntity);
            }
            FileIndexDataEntity fileIndexDataEntityInfo = nurseFileIndexDataMapper.getFileIndexDataInfo(taskExecuteDetailEntity.getEmrFileId(), nurseCode, parentFileIndexDataEntity.getFileIndexDataId());
            if (!StateEnum.PRINT_IDENTIFICATION.getValue().equals(fileIndexDataEntityInfo.getPrintIdentification())) {
                fileIndexDataEntityInfo.setDataValue(userId);
                fileIndexDataEntityInfo.setGmtModify(new Timestamp(date.getTime()));
                fileIndexDataEntityInfo.setPrintIdentification("0");
                nurseFileIndexDataMapper.updateByPrimaryKeySelective(fileIndexDataEntityInfo);
            } else {
                BeanUtils.copyProperties(fileIndexDataEntityInfo, newNurse);
                newNurse.setFileIndexDataId(UUIDUtil.randomString());
                newNurse.setParentFileIndexDataId(parentPrikey);
                newNurse.setDataValue(userId);
                newNurse.setGmtCreate(new Timestamp(date.getTime()));
                newNurse.setGmtModify(new Timestamp(date.getTime()));
                nurseFileIndexDataMapper.insert(newNurse);
            }
        }
        return ResultGenerator.genOkResult();
    }

    @Override
    public Result getNodeState(String qrCode) {
        String backQrCode = transfusionMapper.queryNodeState(qrCode);
        if (StringUtils.isBlank(backQrCode)) {
            // 前台隐藏新增穿刺和通道
            return ResultGenerator.genOkResult("0");
        } else {
            return ResultGenerator.genOkResult("1");
        }
    }

    @Override
    public List<Map<String, String>> getReturnDic() {
        List<Map<String, String>> reDrugs = transfusionMapper.queryDict();
        return reDrugs;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<OrdersFileIndexEntity> saveEndInfusionNew(Map<String, Object> paramMap) {
        String endCode = "sy_jsfs";
        String endTool = "syzx_tool";
        String endLocation = "syzx_position";
        String endNode = "syzx_node";
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        //根据barCode或QrCode获取当前任务节点
        String qrCode = paramMap.get("qrCode").toString();
        String endValue = transfusionMapper.queryVarvalue(endCode);
        String endToolValue = transfusionMapper.queryVarvalue(endTool);
        String endLocationValue = transfusionMapper.queryVarvalue(endLocation);
        String endNodeValue = transfusionMapper.queryVarvalue(endNode);
        List<OrdersFileIndexEntity> fileIndexDataEntityList = transfusionMapper.queryReturnInfo(qrCode, endToolValue, endLocationValue, endNodeValue);

        //TaskExecuteDetailEntity taskExecuteDetailEntity = transfusionMapper.queryTaskExecuteDetail(qrCode, WorkSpaceEnum.INFUSION_COMPLETED.getNodeId());
        TaskExecuteDetailDTO taskExecuteDetailDTO=transfusionMapper.queryTaskExecuteDetailInfo(qrCode, TaskNodeEnum.INFLUSION_AROUD.getValue());
        if (taskExecuteDetailDTO != null) {
            List<OrdersFileIndexDataEntity> fileIndexDataEntitys = transfusionMapper.queryFileIndexList(taskExecuteDetailDTO.getEmrFileId());
            for (int i = 0; i < fileIndexDataEntitys.size(); i++) {
                OrdersFileIndexDataEntity fileIndexDataEntity = fileIndexDataEntitys.get(i);
                if (endValue.equals(fileIndexDataEntity.getElementId())) {
                    fileIndexDataEntity.setDataCode("5939ee58c8fa44fa96e5885b85afc744");    //字典ID，目前给的固定值
                    fileIndexDataEntity.setDataValue("更换输液");   //字典值，目前给定固定值
                    ordersFileIndexDataMapper.updateByPrimaryKeySelective(fileIndexDataEntity);
                }
            }
            patientOrderService.createNextTaskNode(taskExecuteDetailDTO.getTaskExecuteDetailId(),taskExecuteDetailDTO.getBatchNo(), userId, taskExecuteDetailDTO.getGroupId() == null ? "" : taskExecuteDetailDTO.getGroupId(), "", null,qrCode,null);
        }
        Condition condition = new Condition(PuncureChannleEntity.class);
        condition.createCriteria().andEqualTo("inpatorderdataId",taskExecuteDetailDTO.getInpatorderdataId()).andEqualTo("batchNo",taskExecuteDetailDTO.getBatchNo());
        puncureChannleMapper.deleteByCondition(condition);
        return fileIndexDataEntityList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveFile(TaskFileFromViewDTO taskFileFromViewDTO) {
        String message = fileIndexService.saveFileIndex(taskFileFromViewDTO.getEmrFile());
        return ResultGenerator.genOkResult(message);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result infusionInspection(String qrCode) {

        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        String emrFileId = transfusionMapper.queryEmrFileId(qrCode, WorkSpaceEnum.INFUSION_CENTER.getNodeId());

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String currentDate = sdf.format(date);

        //获取退药文书明细主记录
        String parentPrikey = UUIDUtil.randomString();
        FileIndexDataEntity parentFileIndexDataEntity = nurseFileIndexDataMapper.getFileIndexData(emrFileId, StateEnum.INSPECTION_CODE.getValue());
        if (!StateEnum.PRINT_IDENTIFICATION.getValue().equals(parentFileIndexDataEntity.getPrintIdentification())) {
            parentFileIndexDataEntity.setPrintIdentification(StateEnum.PRINT_IDENTIFICATION.getValue());
            parentFileIndexDataEntity.setGmtModify(new Timestamp(date.getTime()));
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(parentFileIndexDataEntity);
        } else {
            FileIndexDataEntity newParent = new FileIndexDataEntity();
            BeanUtils.copyProperties(parentFileIndexDataEntity, newParent);
            newParent.setFileIndexDataId(parentPrikey);
            newParent.setGmtCreate(new Timestamp(date.getTime()));
            newParent.setGmtModify(new Timestamp(date.getTime()));
            nurseFileIndexDataMapper.insert(newParent);
        }
        // 巡视时间
        FileIndexDataEntity inspectionTimeFileIndexDataEntity = nurseFileIndexDataMapper.getFileIndexDataInfo(emrFileId, StateEnum.INSPECTION_TIME_CODE.getValue(), parentFileIndexDataEntity.getFileIndexDataId());
        if (!StateEnum.PRINT_IDENTIFICATION.getValue().equals(inspectionTimeFileIndexDataEntity.getPrintIdentification())) {

            inspectionTimeFileIndexDataEntity.setDataValue(currentDate);
            inspectionTimeFileIndexDataEntity.setPrintIdentification(StateEnum.PRINT_IDENTIFICATION.getValue());
            inspectionTimeFileIndexDataEntity.setGmtModify(new Timestamp(date.getTime()));
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(inspectionTimeFileIndexDataEntity);

        } else {

            FileIndexDataEntity newInspectionDate = new FileIndexDataEntity();
            BeanUtils.copyProperties(inspectionTimeFileIndexDataEntity, newInspectionDate);
            newInspectionDate.setParentFileIndexDataId(parentPrikey);
            newInspectionDate.setFileIndexDataId(UUIDUtil.randomString());
            newInspectionDate.setGmtCreate(new Timestamp(date.getTime()));
            newInspectionDate.setGmtModify(new Timestamp(date.getTime()));
            newInspectionDate.setDataValue(currentDate);
            nurseFileIndexDataMapper.insert(newInspectionDate);

        }
        Map<String, String> currentUser = getCurrentUser();
        String userName = currentUser.get("userName");
        if (StringUtils.isBlank(userName)) {
            userName = "无名";
        }
        // 巡视人
        FileIndexDataEntity signFileIndexDataEntity = nurseFileIndexDataMapper.getFileIndexDataInfo(emrFileId, StateEnum.SIGN_CODE.getValue(), parentFileIndexDataEntity.getFileIndexDataId());
        if (!StateEnum.PRINT_IDENTIFICATION.getValue().equals(signFileIndexDataEntity.getPrintIdentification())) {
            signFileIndexDataEntity.setDataCode(userId);
            signFileIndexDataEntity.setDataValue(userName);
            signFileIndexDataEntity.setPrintIdentification(StateEnum.PRINT_IDENTIFICATION.getValue());
            signFileIndexDataEntity.setGmtModify(new Timestamp(date.getTime()));
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(signFileIndexDataEntity);
        } else {
            FileIndexDataEntity signEntity = new FileIndexDataEntity();
            BeanUtils.copyProperties(signFileIndexDataEntity, signEntity);
            signEntity.setFileIndexDataId(UUIDUtil.randomString());
            signEntity.setParentFileIndexDataId(parentPrikey);
            signEntity.setDataCode(userId);
            signEntity.setDataValue(userName);
            signEntity.setGmtCreate(new Timestamp(date.getTime()));
            signEntity.setGmtModify(new Timestamp(date.getTime()));
            nurseFileIndexDataMapper.insert(signEntity);
        }

        return ResultGenerator.genOkResult();

    }

    /**
     * 获取当前用户信息
     *
     * @return
     */
    public Map<String, String> getCurrentUser() {

        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        Map<String, String> currentUser = transfusionMapper.getUser(userId);
        if (currentUser == null) {
            return new HashMap<String, String>(2);
        }
        return currentUser;

    }


    @Override
    public Result pauseInfusion(Map<String, Object> param) {
        String emrFileId = param.get("emrFileId").toString();
        String surplusVarcode = "sy_syl";
        String surplusDataValue = transfusionMapper.queryVarvalue(surplusVarcode);
        String surplus = null;
        surplus = pauseGetsurplus(emrFileId);
        EmrFileIndexEntity emrFileIndex = emrFileIndexMapper.selectByPrimaryKey(emrFileId);
        int fileSort = emrFileIndexMapper.getFileSort(emrFileId);
        List<Map<String, String>> tplDetailList = emrFileIndexMapper.getTplDetailListByVarCode(WorkSpaceEnum.INFUSION_CENTER.getNodeId(), VarCodeEnum.SY_ZTSY.getVarCode());
        String parentId = UUIDUtil.randomString();
        String finalSurplus = surplus;
        tplDetailList.forEach(tpl -> {
            FileIndexDataEntity fileData = new FileIndexDataEntity();
            if (VarCodeEnum.SY_ZTSY.getVarCode().equals(tpl.get("VAR_CODE"))) {
                fileData.setFileIndexDataId(parentId);
                fileData.setSortId(fileSort);
                fileData.setDataValue(tpl.get("DATA_VALUE"));
            } else {
                fileData.setFileIndexDataId(UUIDUtil.randomString());
                fileData.setSortId(Integer.parseInt(tpl.get("SORT_ID")));
                fileData.setParentFileIndexDataId(parentId);
                if (VarCodeEnum.SY_ZTSJ.getVarCode().equals(tpl.get("VAR_CODE"))) {
                    try {
                        JSONObject jsonFormat = JSONObject.parseObject(tpl.get("ELEMENT_PROPERTY_FORMAT"));
                        String format = jsonFormat.getString("formatValue");
                        DateFormat sdf = new SimpleDateFormat(format);
                        fileData.setDataValue(sdf.format(new Date()));
                    } catch (Exception e) {
                        fileData.setDataValue(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
                        logger.error("转换时间出错", e);
                    }
                } else if (VarCodeEnum.SY_ZTYY.getVarCode().equals(tpl.get("VAR_CODE"))) {
                    fileData.setDataCode(param.get("dataCode").toString());
                    fileData.setDataValue(param.get("dataValue").toString());
                } else if (VarCodeEnum.CK_JLHSQM.getVarCode().equals(tpl.get("VAR_CODE"))) {
                    fileData.setDataValue(getCurrentUser().get("userName"));
                }
            }
            fileData.setDataVersion(emrFileIndex.getDataVersion());
            fileData.setShowIdentification(StateEnum.SHOW_IDENTIFICATION.getValue());
            fileData.setPrintIdentification(tpl.get("PRINT_IDENTIFICATION"));
            fileData.setDeleteIdentification(tpl.get("DELETE_IDENTIFICATION"));
            fileData.setBaseTplDetailId(tpl.get("TPL_ID"));
            fileData.setGmtCreate(new Timestamp(new Date().getTime()));
            fileData.setGmtModify(new Timestamp(new Date().getTime()));
            fileData.setHospitalId(tpl.get("HOSPITAL_ID"));
            fileData.setEmrFileId(emrFileId);
            if (surplusDataValue.equals(tpl.get("ELEMENT_ID"))) {
                fileData.setElementId(tpl.get("ELEMENT_ID"));
                fileData.setPrintIdentification("0");
                fileData.setDataValue(finalSurplus);
            } else {
                fileData.setElementId(tpl.get("ELEMENT_ID"));
            }
            fileData.setTplId(tpl.get("TPL_ID"));
            fileData.setCtlId("0");
            fileData.setOutpatNum(emrFileIndex.getOutpatNum());
            fileData.setInpatNum(emrFileIndex.getInpatNum());
            nurseFileIndexDataMapper.insert(fileData);
        });
        taskExecuteDetailMapper.updateByEmrFileId(emrFileId);
        return ResultGenerator.genOkResult();
    }

    private String pauseGetsurplus(String emrFileId) {
        String speedCode = "syzx_speed";
        String varCode = "sy_syl";
        String typeCode = "sy_dsbq";
        String nurseCode = StateEnum.SIGN_CODE.getValue();
        //获取剩余量比对的文书明细element_id值
        String dataCode = transfusionMapper.queryVarvalue(varCode);
        String nusrseValue = transfusionMapper.queryVarvalue(nurseCode);
        String typeValue = transfusionMapper.queryVarvalue(typeCode);
        String speedValue = transfusionMapper.queryVarvalue(speedCode);
        //获取当前用户ID
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        //定义变量获取医嘱中单位为ML的药品剂量值
        int sum = 0;
        //根据文书ID获取当前病人入院号
        String inpatNum = transfusionMapper.getInpatNum(emrFileId);
        //根据文书ID获取当前任务流程ID
        String taskExecuteId = transfusionMapper.queryTaskExecuteId(emrFileId);
        //根据当前任务流程ID和入院号，获取当前输液医嘱信息
        List<Map<String, String>> drugList = transfusionMapper.queryDurgsByOrderNo(inpatNum, taskExecuteId);
        for (Map<String, String> map : drugList) {
            //获取当前医嘱中单位为ML的剂量值并累加
            if ("ml".equalsIgnoreCase(map.get("unit"))) {
                sum += Integer.parseInt(map.get("itemDosage"));
            }
        }
        //如果当前没有任务流程没有输液记录则记为第一次输液（总量即为剩余量）
        //获取当前时间用以计算剩余量
        Date currentDate = new Date();
        //根据文书ID获取前一次剩余量
        //定义变量获取前一次剩余量
        String preSurplus = null;
        //记录前次操作人
        FileIndexDataEntity preFileIndexDataEntity = new FileIndexDataEntity();
        //获取前次剩余量
        FileIndexDataEntity preSurplusFileIndexDataEntity = new FileIndexDataEntity();
        //记前次操作父数据元
        FileIndexDataEntity parentFileIndexDataEntity = new FileIndexDataEntity();
        //记录前次滴速数据元
        FileIndexDataEntity preSpeedFileIndexDataEntity = new FileIndexDataEntity();
        List<FileIndexDataEntity> fileIndexDataEntityList = transfusionMapper.getAllFileIndexData(emrFileId);
        for (int i = 0; i < fileIndexDataEntityList.size(); i++) {
            //获取前次剩余量
            if (dataCode.equals(fileIndexDataEntityList.get(i).getElementId()) && "0".equals(fileIndexDataEntityList.get(i).getPrintIdentification())) {
                preSurplus = fileIndexDataEntityList.get(i).getDataValue();
                preSurplusFileIndexDataEntity = fileIndexDataEntityList.get(i);
            }
            //获取前次操作人
            if (nusrseValue.equals(fileIndexDataEntityList.get(i).getElementId()) && "0".equals(fileIndexDataEntityList.get(i).getPrintIdentification())) {
                preFileIndexDataEntity = fileIndexDataEntityList.get(i);
            }
            //获取前次操作父数据元
            if (typeValue.equals(fileIndexDataEntityList.get(i).getElementId()) && "0".equals(fileIndexDataEntityList.get(i).getPrintIdentification())) {
                parentFileIndexDataEntity = fileIndexDataEntityList.get(i);
            }
            if (speedValue.equals(fileIndexDataEntityList.get(i).getElementId()) && "0".equals(fileIndexDataEntityList.get(i).getPrintIdentification())) {
                preSpeedFileIndexDataEntity = fileIndexDataEntityList.get(i);
            }
        }
        if (StringUtils.isBlank(preSurplus)) {

        } else {
            //获取前一次剩余量
            sum = Integer.parseInt(preSurplusFileIndexDataEntity.getDataValue());
            //根据文书ID和前一剩余量的父明细ID获取前滴速
            String prespeed = transfusionMapper.queryFileIndexDataSpeed(emrFileId, preSurplusFileIndexDataEntity.getParentFileIndexDataId(), speedCode);
            Integer speedInt = Integer.parseInt(StringUtils.isBlank(prespeed) ? "0" : prespeed);
            //计算当前时间与开始输液时间的时间差(精确到分钟数)
            float differenceTime = (currentDate.getTime() - preSurplusFileIndexDataEntity.getGmtModify().getTime()) / 1000 / 60;
            //计算该段时间内的输液量(时间差乘以滴速除以20    每20滴为1ml)
            int surplus = (int) (differenceTime * speedInt / 20);
            sum = (sum - surplus) >= 0 ? (sum - surplus) : 0;
            //将前一次的剩余量记录，操作人记录设置，父记录设置为隐藏，并创建一条新记录
            //创建新剩余量记录
            FileIndexDataEntity newSurplusFileIndexDataEntity = new FileIndexDataEntity();
            //创建新父数据元记录
            FileIndexDataEntity newParentFileIndexDataEntity = new FileIndexDataEntity();
            //创建新操作人记录
            FileIndexDataEntity newNurseFileIndexDataEntity = new FileIndexDataEntity();
            //创建滴速记录
            FileIndexDataEntity newSpeedFileIndexDataEntity = new FileIndexDataEntity();
            //将前次记录复制数据到新记录
            BeanUtils.copyProperties(preSurplusFileIndexDataEntity, newSurplusFileIndexDataEntity);
            BeanUtils.copyProperties(preFileIndexDataEntity, newNurseFileIndexDataEntity);
            BeanUtils.copyProperties(parentFileIndexDataEntity, newParentFileIndexDataEntity);
            BeanUtils.copyProperties(preSpeedFileIndexDataEntity, newSpeedFileIndexDataEntity);
            //将前次记录隐藏
            preSurplusFileIndexDataEntity.setPrintIdentification("1");
            preFileIndexDataEntity.setPrintIdentification("1");
            parentFileIndexDataEntity.setPrintIdentification("1");
            preSpeedFileIndexDataEntity.setPrintIdentification("1");
            preSpeedFileIndexDataEntity.setShowIdentification("1");
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(preSurplusFileIndexDataEntity);
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(preFileIndexDataEntity);
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(parentFileIndexDataEntity);
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(preSpeedFileIndexDataEntity);
        }
        return Integer.toString(sum);
    }


    @Override
    public Result queryDictByVarCode(String varCode) {
        List<Map<String, String>> list = transfusionMapper.queryDictByVarCode(varCode);
        return ResultGenerator.genOkResult(list);
    }

    @Override
    public Result getSurplus(String emrFileId, String speed) {
        String speedCode = "syzx_speed";
        String varCode = "sy_syl";
        String typeCode = "sy_dsbq";
        String nurseCode = StateEnum.SIGN_CODE.getValue();
        //获取剩余量比对的文书明细element_id值
        String dataCode = transfusionMapper.queryVarvalue(varCode);
        String nusrseValue = transfusionMapper.queryVarvalue(nurseCode);
        String typeValue = transfusionMapper.queryVarvalue(typeCode);
        String speedValue = transfusionMapper.queryVarvalue(speedCode);
        //获取当前用户ID
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        //String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        //定义变量获取医嘱中单位为ML的药品剂量值
        int sum = 0;
        //根据文书ID获取当前病人入院号
        String inpatNum = transfusionMapper.getInpatNum(emrFileId);
        //根据文书ID获取当前任务流程ID
        String taskExecuteId = transfusionMapper.queryTaskExecuteId(emrFileId);
        //根据当前任务流程ID和入院号，获取当前输液医嘱信息
        List<Map<String, String>> drugList = transfusionMapper.queryDurgsByOrderNo(inpatNum, taskExecuteId);
        for (Map<String, String> map : drugList) {
            //获取当前医嘱中单位为ML的剂量值并累加
            if ("ml".equalsIgnoreCase(map.get("unit"))) {
                sum += Integer.parseInt(map.get("itemDosage"));
            }
        }
        //如果当前没有任务流程没有输液记录则记为第一次输液（总量即为剩余量）
        //获取当前时间用以计算剩余量
        Date currentDate = new Date();
        //根据文书ID获取前一次剩余量
        //定义变量获取前一次剩余量
        String preSurplus = null;
        //记录前次操作人
        FileIndexDataEntity preFileIndexDataEntity = new FileIndexDataEntity();
        //获取前次剩余量
        FileIndexDataEntity preSurplusFileIndexDataEntity = new FileIndexDataEntity();
        //记前次操作父数据元
        FileIndexDataEntity parentFileIndexDataEntity = new FileIndexDataEntity();
        //记录前次滴速数据元
        FileIndexDataEntity preSpeedFileIndexDataEntity = new FileIndexDataEntity();
        List<FileIndexDataEntity> fileIndexDataEntityList = transfusionMapper.queryFileIndexData(emrFileId, typeValue);
        for (int i = 0; i < fileIndexDataEntityList.size(); i++) {
            //获取前次剩余量
            if (dataCode.equals(fileIndexDataEntityList.get(i).getElementId()) && "0".equals(fileIndexDataEntityList.get(i).getPrintIdentification())) {
                preSurplus = fileIndexDataEntityList.get(i).getDataValue();
                preSurplusFileIndexDataEntity = fileIndexDataEntityList.get(i);
            }
            //获取前次操作人
            if (nusrseValue.equals(fileIndexDataEntityList.get(i).getElementId()) && "0".equals(fileIndexDataEntityList.get(i).getPrintIdentification())) {
                preFileIndexDataEntity = fileIndexDataEntityList.get(i);
            }
            //获取前次操作父数据元
            if (typeValue.equals(fileIndexDataEntityList.get(i).getElementId()) && "0".equals(fileIndexDataEntityList.get(i).getPrintIdentification())) {
                parentFileIndexDataEntity = fileIndexDataEntityList.get(i);
            }
            if (speedValue.equals(fileIndexDataEntityList.get(i).getElementId()) && "0".equals(fileIndexDataEntityList.get(i).getPrintIdentification())) {
                preSpeedFileIndexDataEntity = fileIndexDataEntityList.get(i);
            }
        }
        if (StringUtils.isBlank(preSurplus)) {
            //若没有上一次剩余量则总量记为剩余量
            preSurplusFileIndexDataEntity.setGmtModify(new Timestamp(new Date().getTime()));
            preSurplusFileIndexDataEntity.setDataValue(Integer.toString(sum));
            preFileIndexDataEntity.setGmtModify(new Timestamp(new Date().getTime()));
            preFileIndexDataEntity.setDataValue(userId);
            preSpeedFileIndexDataEntity.setGmtModify(new Timestamp(new Date().getTime()));
            preSpeedFileIndexDataEntity.setDataValue(speed);
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(preSurplusFileIndexDataEntity);
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(preFileIndexDataEntity);
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(preSpeedFileIndexDataEntity);
            return ResultGenerator.genOkResult("操作成功");
        } else {
            //获取前一次剩余量
            sum = Integer.parseInt(preSurplusFileIndexDataEntity.getDataValue());
            //根据文书ID和前一剩余量的父明细ID获取前滴速
            String prespeed = transfusionMapper.queryFileIndexDataSpeed(emrFileId, preSurplusFileIndexDataEntity.getParentFileIndexDataId(), speedCode);
            Integer speedInt = Integer.parseInt(StringUtils.isBlank(prespeed) ? "0" : prespeed);
            //计算当前时间与开始输液时间的时间差(精确到分钟数)
            float differenceTime = (currentDate.getTime() - preSurplusFileIndexDataEntity.getGmtModify().getTime()) / 1000 / 60;
            //计算该段时间内的输液量(时间差乘以滴速除以20    每20滴为1ml)
            int surplus = (int) (differenceTime * speedInt / 20);
            sum = (sum - surplus) >= 0 ? (sum - surplus) : 0;
            //将前一次的剩余量记录，操作人记录设置，父记录设置为隐藏，并创建一条新记录
            //创建新剩余量记录
            FileIndexDataEntity newSurplusFileIndexDataEntity = new FileIndexDataEntity();
            //创建新父数据元记录
            FileIndexDataEntity newParentFileIndexDataEntity = new FileIndexDataEntity();
            //创建新操作人记录
            FileIndexDataEntity newNurseFileIndexDataEntity = new FileIndexDataEntity();
            //创建滴速记录
            FileIndexDataEntity newSpeedFileIndexDataEntity = new FileIndexDataEntity();
            //将前次记录复制数据到新记录
            BeanUtils.copyProperties(preSurplusFileIndexDataEntity, newSurplusFileIndexDataEntity);
            BeanUtils.copyProperties(preFileIndexDataEntity, newNurseFileIndexDataEntity);
            BeanUtils.copyProperties(parentFileIndexDataEntity, newParentFileIndexDataEntity);
            BeanUtils.copyProperties(preSpeedFileIndexDataEntity, newSpeedFileIndexDataEntity);
            //将前次记录隐藏
            preSurplusFileIndexDataEntity.setPrintIdentification("1");
            preFileIndexDataEntity.setPrintIdentification("1");
            parentFileIndexDataEntity.setPrintIdentification("1");
            preSpeedFileIndexDataEntity.setPrintIdentification("1");
            preSpeedFileIndexDataEntity.setShowIdentification("1");
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(preSurplusFileIndexDataEntity);
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(preFileIndexDataEntity);
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(parentFileIndexDataEntity);
            nurseFileIndexDataMapper.updateByPrimaryKeySelective(preSpeedFileIndexDataEntity);
            //给新数据赋值
            String parentPriKey = UUIDUtil.randomString();
            newParentFileIndexDataEntity.setFileIndexDataId(parentPriKey);
            newParentFileIndexDataEntity.setGmtCreate(new Timestamp(new Date().getTime()));
            newParentFileIndexDataEntity.setGmtModify(new Timestamp(new Date().getTime()));
            newNurseFileIndexDataEntity.setFileIndexDataId(UUIDUtil.randomString());
            newNurseFileIndexDataEntity.setGmtCreate(new Timestamp(new Date().getTime()));
            newNurseFileIndexDataEntity.setGmtModify(new Timestamp(new Date().getTime()));
            newNurseFileIndexDataEntity.setDataValue(userId);
            newNurseFileIndexDataEntity.setParentFileIndexDataId(parentPriKey);
            newSurplusFileIndexDataEntity.setFileIndexDataId(UUIDUtil.randomString());
            newSurplusFileIndexDataEntity.setGmtCreate(new Timestamp(new Date().getTime()));
            newSurplusFileIndexDataEntity.setGmtModify(new Timestamp(new Date().getTime()));
            newSurplusFileIndexDataEntity.setDataValue(Integer.toString(sum));
            newSurplusFileIndexDataEntity.setParentFileIndexDataId(parentPriKey);
            newSpeedFileIndexDataEntity.setFileIndexDataId(UUIDUtil.randomString());
            newSpeedFileIndexDataEntity.setGmtCreate(new Timestamp(new Date().getTime()));
            newSpeedFileIndexDataEntity.setGmtModify(new Timestamp(new Date().getTime()));
            newSpeedFileIndexDataEntity.setDataValue(speed);
            newSpeedFileIndexDataEntity.setParentFileIndexDataId(parentPriKey);
            nurseFileIndexDataMapper.insert(newParentFileIndexDataEntity);
            nurseFileIndexDataMapper.insert(newNurseFileIndexDataEntity);
            nurseFileIndexDataMapper.insert(newSurplusFileIndexDataEntity);
            nurseFileIndexDataMapper.insert(newSpeedFileIndexDataEntity);
            return ResultGenerator.genOkResult("操作成功");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result createChannel(String preQrcode) {
        //根据穿刺任务qrCode及输液中心节点ID获取当前穿刺信息中的穿刺点，穿刺位置，穿刺工具信息
        FileIndexDataEntity fileIndexDataEntity = nurseFileIndexDataMapper.queryDataEntity(preQrcode, TaskNodeEnum.INFLUSION_AROUD.getValue());
        List<Map<String, Object>> list = nurseFileIndexDataMapper.queryFileIndexData("ccxx_bq", fileIndexDataEntity.getEmrFileId());
        String parentId = list.get(0).get("FILE_INDEX_DATA_ID").toString();
        //获取当前父节点文书明细信息
//        FileIndexDataEntity nowParentFileIndexDataEntity = nurseFileIndexDataMapper.queryDataEntity(nowQrcode,WorkSpaceEnum.INFUSION_CENTER.getNodeId());
        Map<String, String> tempMap = new HashMap<>();
        List<Map<String, Object>> newList = list.stream().map(map -> {
            String newId = UUIDUtil.randomString();
            String oldId = (String) map.get("FILE_INDEX_DATA_ID");
            String oldParentId = (String) map.get("PARENT_FILE_INDEX_DATA_ID");
            String elementProperty = (String) map.get("ELEMENT_PROPERTY");
            Map propertyMap = JSONObject.parseObject(elementProperty, Map.class);
            if(null == propertyMap){
                propertyMap = new HashMap();
            }
            propertyMap.put("editIdentification", "1");
            map.put("ELEMENT_PROPERTY", JSONObject.toJSONString(propertyMap));
            map.put("FILE_INDEX_DATA_ID", newId);
            tempMap.put(oldId, newId);
            if (tempMap.get(oldParentId) != null) {
                map.put("PARENT_FILE_INDEX_DATA_ID", tempMap.get(oldParentId));
            }
            return map;
        }).collect(Collectors.toList());
//        for (int i = 0; i < preFileIndexDataEntityList.size(); i++) {
//            FileIndexDataEntity fileIndexDataEntity = new FileIndexDataEntity();
//            if (!preFileIndexDataEntityList.get(i).getElementId().equals(nowParentFileIndexDataEntity.getElementId())) {
//                //将新增穿刺中的穿刺信息文书明细复制到新增通道文书明细
//                BeanUtils.copyProperties(preFileIndexDataEntityList.get(i), fileIndexDataEntity);
//                //修改复制后的主键ID避免插入数据时冲突
//                fileIndexDataEntity.setFileIndexDataId(UUIDUtil.randomString());
//                fileIndexDataEntity.setGmtCreate(new Date());
//                fileIndexDataEntity.setGmtModify(new Date());
//                fileIndexDataEntity.setEmrFileId(nowParentFileIndexDataEntity.getEmrFileId());
//                //将修改后的文书明细返回前台
//                fileIndexDataEntity.setParentFileIndexDataId(nowParentFileIndexDataEntity.getFileIndexDataId());
//                nurseFileIndexDataMapper.insert(fileIndexDataEntity);
//            }
//        }
        List<EmrFileData> fileDataList = convertData2(newList);
        List<EmrFileData> newFileData = buildTreeData(fileDataList, parentId);
        return ResultGenerator.genOkResult(newFileData);
    }

    /**
     * 结束时间计算
     *
     * @param emrFileId
     * @return
     */
    private Map<String, String> endInfusionCount(String emrFileId, String inpatOrderId, String taskExecuteId) {
        //根据文书ID获取当前文书对应的滴速
        Map<String, String> speedFileIndexDataMap = nurseFileIndexDataMapper.getDataEntity(emrFileId);
        //获取当前最新剩余量
        Map<String, String> surplusFileIndexDataMap = nurseFileIndexDataMapper.getSurPlus(emrFileId);

        List<Map<String, String>> drugs = transfusionMapper.queryDurgsByInpatOrderId(inpatOrderId);

        String beginDatetime = transfusionMapper.queryInfusionBeginTime(taskExecuteId, TaskNodeEnum.INFLUSION_NEW.getValue());

        //获取最近剩余量的开始时间
        String currentTime = surplusFileIndexDataMap.get("gmtModify");
        Date currDate = DateUtil.stringToDate(currentTime);

        Map<String, String> resultMap = new HashMap<>();

        long endTime = 0;
        long time = 0;
        float persent = 0f;
        boolean isEndNul = true;
        //计算结束时间(根据最近剩余量及最近滴速计算出还需要输液的时间)
        if (speedFileIndexDataMap.get("dataValue") != null
                && surplusFileIndexDataMap.get("dataValue") != null
                && surplusFileIndexDataMap.get("unit").equalsIgnoreCase("ml")
                && speedFileIndexDataMap.get("unit").equalsIgnoreCase("滴/分钟")) {
            Float speed = Float.parseFloat(speedFileIndexDataMap.get("dataValue"));
            Float surplus = Float.parseFloat(surplusFileIndexDataMap.get("dataValue"));

            resultMap.put("surplus", String.valueOf(surplus));
            resultMap.put("speed", String.valueOf(speed));

            Float perDropValume = 1f / 20; // 1滴相当于1/20ml
            Float valumeOfPerSecond = speed / 60; // 每秒滴数
            long subSconds = (new Date().getTime() - currDate.getTime()) / 1000; // 当前时间和剩余量更新时间的差值
            float useValume = valumeOfPerSecond * subSconds * perDropValume;

            time = (long) (surplus * 20 * 60 * 1000 / speed);
            Float sum = 0F;
            if (ArrayUtils.isNotEmpty(drugs.toArray())) {
                for (Map<String, String> map : drugs) {
                    if (map.get("unit").equalsIgnoreCase("ml")) {
                        sum = sum + Float.parseFloat(map.get("dosage"));
                    }
                }

                if (sum >= surplus && (useValume + surplus) < sum) {
                    persent = useValume + surplus / sum;
                } else if (sum >= surplus && (useValume + surplus) >= sum) {
                    persent = 1;
                }
            }
            if (null != speed && "0".equals(String.valueOf(speed))) {
                isEndNul = false;
            }
        }
        endTime = time + currDate.getTime();
        Date endDate = new Date(endTime);

        if (isEndNul) {
            resultMap.put("endDatetime", DateUtil.dateToString(endDate, "yyyy-MM-dd HH:mm:ss"));
        }
        resultMap.put("persent", String.valueOf(persent));
        resultMap.put("currentTime", currentTime);
        resultMap.put("beginDatetime", beginDatetime);

        return resultMap;
    }


    @Override
    public Map<String, Object> endInfusionInfo(String emrFileId) {
        //根据文书ID获取当前文书对应的滴速
        Map<String, String> speedFileIndexDataMap = nurseFileIndexDataMapper.getDataEntity(emrFileId);
        //获取当前最新剩余量
        Map<String, String> surplusFileIndexDataMap = nurseFileIndexDataMapper.getSurPlus(emrFileId);
        //获取药品总量
        Map<String, String> drugsFileIndexDataMap = nurseFileIndexDataMapper.getDrugsSum(emrFileId);
        //获取开始时间
        String startTime = drugsFileIndexDataMap.get("gmtModify");
        //获取最近剩余量的开始时间
        String currentTime = surplusFileIndexDataMap.get("gmtModify");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date current = null;
        try {
            current = sdf.parse(currentTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long endTime = 0;
        long time = 0;
        //计算结束时间(根据最近剩余量及最近滴速计算出还需要输液的时间)
        if (surplusFileIndexDataMap.get("dataValue") != null) {
            time = Long.parseLong(surplusFileIndexDataMap.get("dataValue")) * 20 * 60 * 1000 / Integer.parseInt(speedFileIndexDataMap.get("dataValue"));
        }
        endTime = time + current.getTime();
        Date endDate = new Date(endTime);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("speed", speedFileIndexDataMap.get("dataValue") + speedFileIndexDataMap.get("unit"));
        resultMap.put("allDrugs", drugsFileIndexDataMap.get("dataValue") + drugsFileIndexDataMap.get("unit"));
        resultMap.put("surplus", surplusFileIndexDataMap.get("dataValue") + surplusFileIndexDataMap.get("unit"));
        try {
            resultMap.put("startTime", sdf.format(sdf.parse(startTime)));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        resultMap.put("endTime", sdf.format(endDate));
        return resultMap;
    }

    @Override
    public Result getDefaultPuncture(String qrCode) {
        String infusionType = null;
        String varCode = "syzx_node";
        //根据qrCode获取病人入院号
        String inpatNum = transfusionMapper.queryInfoByBarCode(qrCode);
        // 根据当前病人入院号获取该病人未完成的输液流程明细，获取其中的文书id
        List<Map<String, Object>> emrFileIds = transfusionMapper.queryEmrFileIds(inpatNum, TaskNodeEnum.INFLUSION_NEW.getValue());
        if (emrFileIds.size() == 0) {
            infusionType = "A";
        } else {
            //获取未完成输液文书
            List<FileIndexDataSmallEntity> list = transfusionMapper.getFileIndexData(emrFileIds);
            List<String> typeList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getDataValue() != null) {
                    typeList.add(list.get(i).getDataValue().toString());
                }
            }

            if (!typeList.contains("A")) {
                infusionType = "A";
            } else if (!typeList.contains("B")) {
                infusionType = "B";
            } else if (!typeList.contains("B")) {
                infusionType = "B";
            } else if (!typeList.contains("C")) {
                infusionType = "C";
            } else if (!typeList.contains("D")) {
                infusionType = "D";
            } else if (!typeList.contains("E")) {
                infusionType = "E";
            } else if (!typeList.contains("F")) {
                infusionType = "F";
            } else if (!typeList.contains("G")) {
                infusionType = "G";
            } else if (!typeList.contains("H")) {
                infusionType = "H";
            } else if (!typeList.contains("I")) {
                infusionType = "I";
            } else if (!typeList.contains("J")) {
                infusionType = "J";
            } else if (!typeList.contains("K")) {
                infusionType = "K";
            } else if (!typeList.contains("L")) {
                infusionType = "L";
            } else if (!typeList.contains("M")) {
                infusionType = "M";
            } else if (!typeList.contains("N")) {
                infusionType = "N";
            }
        }
        //获取当前任务对应的穿刺点明细
        Map<String, String> map = new HashMap<>();
        map.put("varCode", varCode);
        map.put("infusionType", infusionType);
        return ResultGenerator.genOkResult(map);
    }

    @Override
    public Result endInfusionType() {
        List<Map<String, String>> resultMap = transfusionMapper.queryEndInfusionType();
        return ResultGenerator.genOkResult(resultMap);
    }

    @Override
    public Result getInfusions(String qrCode) {
        String inpatNum = transfusionMapper.queryInfoByBarCode(qrCode);
        Map<String, Object> resultMap = new HashMap<String, Object>(2);

        // 根据入院号获取当前病人信息（姓名，入院号，年龄，床号，性别）
//        Map<String, String> patientMap = transfusionMapper.queryPatientInfo(inpatNum);
        // 根据当前病人入院号获取该病人未完成的输液流程明细，获取其中的文书id
        List<Map<String, Object>> emrFileIds = transfusionMapper.queryInfusionCenterEmrFileIds(inpatNum, TaskNodeEnum.INFLUSION_AROUD.getValue());
        List<FileIndexDataSmallEntity> list = transfusionMapper.getFileIndexData(emrFileIds);

        for (Map map : emrFileIds) {
            String surplus = "0";
            for (FileIndexDataSmallEntity smallEntity : list) {
                if (map.get("emrFileId").toString().equals(smallEntity.getEmrFileId())) {
                    if (smallEntity.getVarCode().equals("syzx_node")) {
                        map.put("node", smallEntity.getDataValue() == null ? "-" : smallEntity.getDataValue());
                    } else if (smallEntity.getVarCode().equals("syzx_position")) {
                        map.put("position", smallEntity.getDataValue() == null ? "" : smallEntity.getDataValue());
                    } else if (smallEntity.getVarCode().equals("syzx_tool")) {
                        map.put("tool", smallEntity.getDataValue() == null ? "" : smallEntity.getDataValue());
                    } else if (smallEntity.getVarCode().equals("syzx_passstate")) {
                        map.put("state", smallEntity.getDataValue() == null ? "" : smallEntity.getDataValue());
                    } else if (smallEntity.getVarCode().equals("syzx_speed")) {
                        map.put("speed", smallEntity.getDataValue() == null ? "1" : smallEntity.getDataValue());
                        map.put("unit", smallEntity.getUnit() == null ? "滴/分钟" : smallEntity.getUnit());
                    } else if (smallEntity.getVarCode().equals("sy_syl")) {
                        surplus = StringUtils.isBlank(smallEntity.getDataValue()) ? "0" : smallEntity.getDataValue();
                    }
                }
            }

            Map<String, String> endInfusionMap = endInfusionCount(map.get("emrFileId").toString(), map.get("inpatOrderId").toString(), map.get("taskExecuteId").toString());
            map.put("endInfusions", endInfusionMap);
            if (endInfusionMap.get("beginDatetime") != null) {
                map.put("beginDatetime", endInfusionMap.get("beginDatetime"));
            }

            // 获取组医嘱药品
            List<Map<String, String>> drugList = transfusionMapper.queryDurgsByOrderNo(inpatNum, map.get("taskExecuteId").toString());
            map.put("drugs", drugList);

            // 计算滴速
            Float milliliter = 0.0f;
            int sum = 0;
            for (Map<String, String> drugMap : drugList) {
                if ("g".equalsIgnoreCase(drugMap.get("unit").toString())) {
                    milliliter += Float.parseFloat(drugMap.get("itemDosage").toString());
                } else if ("ml".equalsIgnoreCase(drugMap.get("unit").toString())) {
                    sum += Integer.parseInt(drugMap.get("itemDosage").toString());
                }
            }
            if ("滴/分钟".equalsIgnoreCase(map.get("unit").toString())) {
                Float seconds = (milliliter / Float.parseFloat(map.get("speed").toString())) * 60 * 20;
                map.put("seconds", seconds);
            } else if ("ml/h".equalsIgnoreCase(map.get("unit").toString())) {
                Float seconds = (milliliter / Float.parseFloat(map.get("speed").toString())) * 60 * 60;
                map.put("seconds", seconds);
            }
            //计算剩余量百分比
            float surplusPercent = 0.0f;
            if (sum != 0) {
                surplusPercent = (sum - Integer.parseInt(surplus)) / sum;
            } else {
                surplusPercent = 0.0f;
            }
            map.put("surplus", surplusPercent);
            // 组装节点
            if (resultMap.containsKey(map.get("node").toString())) {
                List nodes = (List) resultMap.get(map.get("node").toString());
                nodes.add(map);
            } else {
                List nodes = new ArrayList();
                nodes.add(map);
                resultMap.put(map.get("node").toString(), nodes);
            }
        }

        // List resultList = resultMap.values().stream().collect(Collectors.toList());
        List resultList = new ArrayList();
        for (String node : resultMap.keySet()) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("index", node);
            map.put("node", resultMap.get(node));
            resultList.add(map);
        }

        return ResultGenerator.genOkResult(resultList);
    }

    public Result getMedicineNum(String wardId, String currentDate, String currentTime) {
        //根据当前日期及病区ID获取该病区当天所有的静配领药任务（待领及已领）

        return null;
    }

    @Override
    public Result getInfusionCenter(String inpatNum) {
        Map<String, Object> resultMap = new HashMap<String, Object>(2);

        // 根据入院号获取当前病人信息（姓名，入院号，年龄，床号，性别）
//        Map<String, String> patientMap = transfusionMapper.queryPatientInfo(inpatNum);
        // 根据当前病人入院号获取该病人未完成的输液流程明细，获取其中的文书id
        List<Map<String, Object>> emrFileIds = transfusionMapper.queryInfusionCenterEmrFileIds(inpatNum, TaskNodeEnum.INFLUSION_AROUD.getValue());
        // 如果为空直接返回
        if (CollectionUtils.isEmpty(emrFileIds)) {
            return ResultGenerator.genOkResult(new ArrayList<>());
        }
        List<FileIndexDataSmallEntity> list = transfusionMapper.getFileIndexData(emrFileIds);

        for (Map map : emrFileIds) {
            String surplus = "0";
            for (FileIndexDataSmallEntity smallEntity : list) {
                if (map.get("emrFileId").toString().equals(smallEntity.getEmrFileId())) {
                    if (smallEntity.getVarCode().equals("syzx_node")) {
                        map.put("node", smallEntity.getDataValue() == null ? "-" : smallEntity.getDataValue());
                    } else if (smallEntity.getVarCode().equals("syzx_position")) {
                        map.put("position", smallEntity.getDataValue() == null ? "" : smallEntity.getDataValue());
                    } else if (smallEntity.getVarCode().equals("syzx_tool")) {
                        map.put("tool", smallEntity.getDataValue() == null ? "" : smallEntity.getDataValue());
                    } else if (smallEntity.getVarCode().equals("syzx_passstate")) {
                        map.put("state", smallEntity.getDataValue() == null ? "" : smallEntity.getDataValue());
                    } else if (smallEntity.getVarCode().equals("syzx_speed")) {
                        map.put("speed", smallEntity.getDataValue() == null ? "1" : smallEntity.getDataValue());
                        map.put("unit", smallEntity.getUnit() == null ? "滴/分钟" : smallEntity.getUnit());
                    } else if (smallEntity.getVarCode().equals("sy_syl")) {
                        surplus = StringUtils.isBlank(smallEntity.getDataValue()) ? "0" : smallEntity.getDataValue();
                    }
                }
            }

            Map<String, String> endInfusionMap = endInfusionCount(map.get("emrFileId").toString(), map.get("inpatOrderId").toString(), map.get("taskExecuteId").toString());
            map.put("endInfusions", endInfusionMap);

            if (endInfusionMap.get("beginDatetime") != null) {
                map.put("beginDatetime", endInfusionMap.get("beginDatetime"));
            }
            // 获取组医嘱药品
            List<Map<String, String>> drugList = transfusionMapper.queryDurgsByOrderNo(inpatNum, map.get("taskExecuteId").toString());
            map.put("drugs", drugList);

            // 计算滴速
            Float milliliter = 0.0f;
            int sum = 0;
            for (Map<String, String> drugMap : drugList) {
                if ("g".equalsIgnoreCase(drugMap.get("unit").toString())) {
                    milliliter += Float.parseFloat(drugMap.get("itemDosage").toString());
                } else if ("ml".equalsIgnoreCase(drugMap.get("unit").toString())) {
                    sum += Integer.parseInt(drugMap.get("itemDosage").toString());
                }
            }
            if ("滴/分钟".equalsIgnoreCase(map.get("unit").toString())) {
                Float seconds = (milliliter / Float.parseFloat(map.get("speed").toString())) * 60 * 20;
                map.put("seconds", seconds);
            } else if ("ml/h".equalsIgnoreCase(map.get("unit").toString())) {
                Float seconds = (milliliter / Float.parseFloat(map.get("speed").toString())) * 60 * 60;
                map.put("seconds", seconds);
            }
            //计算剩余量百分比
            float surplusPercent = 0.0f;
            if (sum != 0) {
                surplusPercent = (sum - Integer.parseInt(surplus)) / sum;
            } else {
                surplusPercent = 0.0f;
            }
            map.put("surplus", surplusPercent);
            // 组装节点
            if (resultMap.containsKey(map.get("node").toString())) {
                List nodes = (List) resultMap.get(map.get("node").toString());
                nodes.add(map);
            } else {
                List nodes = new ArrayList();
                nodes.add(map);
                resultMap.put(map.get("node").toString(), nodes);
            }
        }

        // List resultList = resultMap.values().stream().collect(Collectors.toList());
        List resultList = new ArrayList();
        for (String node : resultMap.keySet()) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("index", node);
            map.put("node", resultMap.get(node));
            resultList.add(map);
        }

        return ResultGenerator.genOkResult(resultList);
    }

    @Override
    public Result infusionCenterList(String qrCode) {
        //根据住院号，获得所有的穿刺部位等信息
        List<PuncureChannleVo> puncureChannleEntities = puncureChannleMapper.selectInfoByQrCode(qrCode);
        return ResultGenerator.genOkResult(puncureChannleEntities);
    }
}
